package com.jwsoft.manager.core.util.dySync;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 调用工具类
 * @Author zhiyuan
 * @Date 2024/4/18 15:29
 */
@Component
public class CallUtils {

    /**
     * 请求签名
     * @param data
     * @param privateKey
     * @param timestamp
     * @return
     */
    public String getSign(String data,String privateKey,String timestamp){
        String jointStr = serializeData(data) + "&secret=" + privateKey + "&timestamp=" + timestamp;
        String encryptStr = SmUtil.sm3(jointStr).toUpperCase();
        return encryptStr;
    }

    public String serializeData(String jsonStr){
        if (StringUtils.isBlank(jsonStr)){
            return "";
        }
        Map map = (Map) JSON.parse(jsonStr, JSONReader.Feature.IgnoreSetNullValue);
        return JSON.toJSONString(map, JSONWriter.Feature.MapSortField);
    }

    /**
     * 请求加密
     * @param content
     * @param publicKey
     * @return
     */
    public String encrypt(String content, String publicKey) {
        SM2 sm2 = SmUtil.sm2(null, publicKey);
        String result = sm2.encryptHex(content, KeyType.PublicKey);
        return result;
    }


    /**
     * 请求解密
     * @param content
     * @param privateKey
     * @return
     */
    public String decrypt(String content, String privateKey) {
        SM2 sm2 = SmUtil.sm2(privateKey, null);
        sm2.setMode(SM2Engine.Mode.C1C3C2);
        String result = StrUtil.utf8Str(sm2.decryptFromBcd(content, KeyType.PrivateKey));
        return result;
    }
}
